﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core;
using Cofe.Core.Security;
using Cofe.Web.Utils;

namespace Cofe.Web.Models
{
    public class UserInfoViewModel
    {
        private class identityStub : IIdentity
        {

            public string AuthenticationType { get; set; }
            public bool IsAuthenticated { get; set; }
            public string Name { get; set; }            
        }

        #region Constructor
        
        #endregion

        #region Methods
       
        
        #endregion

        #region Data
        
        #endregion

        #region Public Properties

        public string AuthenticateType { get; set; }
        public string AccountName { get; set; }
        public WebUserRole Role { get; set; }
        public bool IsAdmin { get { return Role.HasFlag(WebUserRole.Admin); } }
        public string RoleString { get { return WebUserRoleUtils.GetRoleString(Role); } set { Role = WebUserRoleUtils.GetRole(value); } }
        
        #endregion

        public static UserInfoViewModel FromIdentity(IIdentity identity)
        {
            
            IPrincipal principal = CofeServices.SecurityManager.UserManager.GetPrincipal(identity);

            WebUserRole role = WebUserRole.Other;
            foreach (var r in WebUserRoleUtils.PossibleRoles)
                if (principal.IsInRole(WebUserRoleUtils.GetRoleString(r)))
                {
                    role = r;
                    break;
                }

            return new UserInfoViewModel()
            {
                Role = role,
                AccountName = principal.Identity.Name,
                AuthenticateType = principal.Identity.AuthenticationType
            };
        }

        public static UserInfoViewModel FromUser(string userName, string authenticateType)
        {
            IIdentity identity = new identityStub() { AuthenticationType = authenticateType, IsAuthenticated = true, Name = userName };
            return FromIdentity(identity);
        }
    }
}
